package cn.jksoft.businessclient.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.jakewharton.rxbinding.widget.RxTextView;
import com.yokeyword.indexablelistview.IndexEntity;
import com.yokeyword.indexablelistview.IndexableStickyListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jksoft.businessclient.R;
import cn.jksoft.businessclient.api.ReceivingApi;
import cn.jksoft.businessclient.api.ReceivingService;
import cn.jksoft.businessclient.base.BaseApplication;
import cn.jksoft.businessclient.base.BaseSwipeBackCompatActivity;
import cn.jksoft.businessclient.bean.BaseEntity;
import cn.jksoft.businessclient.bean.CheckOrderEntity;
import cn.jksoft.businessclient.bean.CustomerEntity;
import cn.jksoft.businessclient.bean.FastCreateOrderEntity;
import cn.jksoft.businessclient.ui.adapter.CustomerSelectAdapter;
import cn.jksoft.businessclient.utils.DialogHelp;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

/**
 * Created by RogersHuang on 16/4/8.
 */
public class FastCreateOrderActivity extends BaseSwipeBackCompatActivity implements View.OnClickListener {
    @Bind(R.id.tv_input)
    TextView tvInput;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_car_num)
    TextView tvCarNum;
    @Bind(R.id.btn_delete)
    ImageButton btnDelete;
    @Bind(R.id.tv_clear)
    TextView tvClear;
    @Bind(R.id.tv_equal)
    TextView tvEqual;
    @Bind(R.id.tv_point)
    TextView tvPoint;
    @Bind(R.id.tv_add)
    TextView tvAdd;
    @Bind(R.id.tv_hint_price)
    TextView tvHintPrice;
    @Bind(R.id.btn_create_order)
    Button btnCreateOrder;
    private long customerId,custCmId;
    private ProgressDialog waitDialog;
    private String carPlateNum;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_create_fast);
        ButterKnife.bind(this);
        initTitle("快捷开单");
        initBackClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initRx();
    }

    private void initRx(){
        rx.Observable<CharSequence> accountObservable = RxTextView.textChanges(tvInput);
        rx.Observable<CharSequence> pwdObservable = RxTextView.textChanges(tvCarNum);
        rx.Observable.combineLatest(accountObservable,
                pwdObservable,
                new Func2<CharSequence, CharSequence, Boolean>() {
                    @Override
                    public Boolean call(CharSequence newAccount,
                                        CharSequence newPassword) {
                        boolean accountValid = newAccount.length()>0;
                        boolean pwdValid = newPassword.length()>0;
                        return accountValid;

                    }
                }).subscribe(new Observer<Boolean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(Boolean isValid) {
                btnDelete.setEnabled(isValid);
                tvClear.setClickable(isValid);
                tvPoint.setClickable(isValid);
                tvEqual.setClickable(isValid);
                tvAdd.setClickable(isValid);
                tvHintPrice.setVisibility(isValid?View.GONE:View.VISIBLE);
                btnCreateOrder.setEnabled((customerId!=0 && custCmId!=0&&isValid));
            }
        });
    }

    private void fastCreateOrder (){
        waitDialog = DialogHelp.getWaitDialog(this, "正在下单，请稍后...");
        waitDialog.show();
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId());
            json.put("operId",BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getAdminUserId());
            json.put("tenantId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getTenantId());
            json.put("customerId", customerId);
            json.put("custCmId", custCmId);
            json.put("orderTotalMoney",tvInput.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ReceivingApi service = ReceivingService.createReceivingService();
        service.fastCreateOrder(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<FastCreateOrderEntity>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(FastCreateOrderEntity entity) {

                        String retCode = entity.getIs_successful();
                        if ("1".equals(retCode)) {
                            waitDialog.dismiss();
                            Bundle bundle = new Bundle();
                            bundle.putString("outboundId", entity.getOrderInfo().getOutboundId());
                            bundle.putString("carPlateNum", carPlateNum);
                            bundle.putString("messageId",entity.getOrderInfo().getMessId());
                            bundle.putBoolean("isFastCreate",true);
                            readyGoForResult(OrderSettlementActivity.class,0, bundle);
                        }else{
                            showToast(entity.getResult());
                        }
                    }
                });
    }

    private void calculatePrice(){
        String[] inputArray =tvInput.getText().toString().split("\\+");
        float total = 0;
        for (String number : inputArray){
            total = total+Float.parseFloat(number);
        }
        if(total<1) {
            tvInput.setText(new DecimalFormat("0.00").format(total));
        }else{
            tvInput.setText(new DecimalFormat(".00").format(total));
        }
    }


    @Override
    @OnClick({R.id.info_layout,R.id.btn_create_order,R.id.btn_delete,R.id.tv_clear,R.id.tv_0,R.id.tv_1,R.id.tv_2,
            R.id.tv_3,R.id.tv_4,R.id.tv_5,R.id.tv_6,R.id.tv_7,R.id.tv_8,R.id.tv_9,R.id.tv_point,R.id.tv_equal,R.id.tv_add})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.info_layout:
                readyGoForResult(CustomerSelectActivity.class, 0);
                break;
            case R.id.btn_create_order:
                if(customerId==0 || custCmId==0){
                    showToast("请选择客户");
                    return;
                }
                calculatePrice();
                fastCreateOrder();
                break;
            case R.id.btn_delete:
                tvInput.setText(tvInput.getText().toString().substring(0, tvInput.getText().length() - 1));
                break;
            case R.id.tv_clear:
                tvInput.setText("");
                break;
            case R.id.tv_equal:
                calculatePrice();
                break;
            case R.id.tv_add:
                if(!tvInput.getText().toString().substring(tvInput.getText().length()-1).equals("+")){
                    tvInput.setText(tvInput.getText() + "+");
                }
                break;
            case R.id.tv_point:
                String[] inputArray =tvInput.getText().toString().split("\\+");
                String lastInput = null;
                for (String number : inputArray){
                    lastInput = number;
                }
                if(!lastInput.contains(".")){
                    if(tvInput.getText().toString().substring(tvInput.getText().length()-1).equals("+")){
                        tvInput.setText(tvInput.getText() + "0.");
                    }else {
                        tvInput.setText(tvInput.getText() + ".");
                    }
                }
                break;
            default:
                TextView tvNumber = (TextView) v;
                tvInput.setText(tvInput.getText() + tvNumber.getText().toString());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            customerId = data.getExtras().getLong("customerId");
            custCmId = data.getExtras().getLong("custCmId");
            tvName.setText(data.getExtras().getString("customerName"));
            carPlateNum = data.getExtras().getString("carPlateNum");
            tvCarNum.setText(carPlateNum);
        }
    }
}
